package com.jspgou.cms.manager.impl;

import static com.jspgou.common.web.Constants.POINT;
import static com.jspgou.common.web.Constants.SPT;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.jspgou.cms.dao.ShopMemberDao;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.ShopMemberAddress;
import com.jspgou.cms.entity.ShopMemberGroup;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.CartMng;
import com.jspgou.cms.manager.RoleMng;
import com.jspgou.cms.manager.ShopMemberAddressMng;
import com.jspgou.cms.manager.ShopMemberGroupMng;
import com.jspgou.cms.manager.ShopMemberMng;
import com.jspgou.common.file.FileNameUtils;
import com.jspgou.common.hibernate3.Updater;
import com.jspgou.common.image.ImageScale;
import com.jspgou.common.image.ImageUtils;
import com.jspgou.common.page.Pagination;
import com.jspgou.core.entity.Member;
import com.jspgou.core.entity.User;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.MemberMng;
import com.jspgou.core.manager.UserMng;
import com.jspgou.core.manager.WebsiteMng;
import com.jspgou.core.resolver.RealPathResolver;

@Service
@Transactional
public class ShopMemberMngImpl implements ShopMemberMng {
	public ShopMember getByUserId(Long webId, Long userId) {
		Member coreMember = memberMng.getByUserId(webId, userId);
		if (coreMember != null) {
			return findById(coreMember.getId());
		} else {
			return null;
		}
	}

	public ShopMember getByUsername(Long webId, String username) {
		Member coreMember = memberMng.getByUsername(webId, username);
		if (coreMember == null) {
			return null;
		}
		return findById(coreMember.getId());
	}

	public ShopMember register(String username, String password, String email,Boolean active,String activationCode,
			Long[] roleIds,String realName,String ip, Boolean disabled, Long webId,Long groupId,
			ShopMember member,Store store) {
		Website web = websiteMng.findById(webId);
		if (member == null) {
			member = new ShopMember();
		}
		Member coreMember = memberMng.register(username, password, email,active,activationCode, ip,
				disabled, web);
		member.setMember(coreMember);
		member.setWebsite(web);
		member.setFreezeScore(0);
		if(store!=null){
			member.setStore(store);
			member.setIsEmployee(true);
		}else{
			member.setIsEmployee(false);
		}
		if (groupId != null) {
			member.setGroup(shopMemberGroupMng.findById(groupId));
		}
		if(StringUtils.isNotBlank(realName)){
			member.setRealName(realName);
		}	
		//添加角色
		if (!ArrayUtils.isEmpty(roleIds)) {
			for (Long rid : roleIds) {
				member.addToRoles(roleMng.findById(rid));
			}
		}
		if(store!=null){
			member.addToStores(store);
		}
		return save(member);
	}

	public ShopMember join(String username, Long webId, Long groupId) {
		Website web = websiteMng.findById(webId);
		Member coreMember = memberMng.join(username, web);
		ShopMember member = new ShopMember();
		member.setMember(coreMember);
		member.setWebsite(web);
		member.setGroup(shopMemberGroupMng.findById(groupId));
		return save(member);
	}

	public ShopMember join(Long userId, Long webId, ShopMemberGroup group) {
		User user = userMng.findById(userId);
		return join(user, webId, group);
	}

	public ShopMember join(User user, Long webId, ShopMemberGroup group) {
		Website web = websiteMng.findById(webId);
		Member coreMember = memberMng.join(user, web);
		ShopMember member = new ShopMember();
		member.init();
		member.setMember(coreMember);
		member.setWebsite(web);
		member.setGroup(group);
		return save(member);
	}

	public ShopMember register(String username, String password, String email,Boolean active,
			String activationCode,Long[] roleIds,String realName,String ip, Boolean disabled, 
			Long webId, Long groupId,Store store) {
		
		return register(username, password, email,active,activationCode,roleIds,realName,ip, disabled, webId,
				groupId, new ShopMember(),store);
	}
	
	public Pagination getPage(Long webId, int pageNo, int pageSize){
		Pagination page = dao.getPage(webId, pageNo, pageSize);
		return page;
	}

	@Transactional(readOnly = true)
	public Pagination getPage(Long webId,Long storeId,Boolean isEmployee, int pageNo, int pageSize) {
		Pagination page = dao.getPage(webId,storeId, isEmployee,pageNo, pageSize);
		return page;
	}

	@Transactional(readOnly = true)
	public ShopMember findById(Long id) {
		ShopMember entity = dao.findById(id);
		return entity;
	}
	
	public ShopMember updateAvatar(Website web,ShopMember member,MultipartFile file){//会员中心更改图像(wang ze wu)
		String uploadPath = realPathResolver.get(web.getUploadRel());
		
		saveImage(member, file, uploadPath);
		return member;
	}

	private boolean saveImage(ShopMember member,MultipartFile file, String uploadPath) {
		// 如果没有上传文件，则不处理。
		if (file == null || file.isEmpty()) {
			return false;
		}
		// 先删除图片，如果有的话。
		deleteImage(member, uploadPath);
		// 获得后缀
		String ext = FilenameUtils.getExtension(file.getOriginalFilename());
		// 检查后缀是否允许上传
		if (!ImageUtils.isImage(ext)) {
			return false;
		}
		// 日期目录
		String dateDir = FileNameUtils.genPathName();
		// 创建目录
		File root = new File(uploadPath, dateDir);
		// 相对路径
		String relPath = SPT + dateDir + SPT;
		if (!root.exists()) {
			root.mkdirs();
		}
		// 取文件名
		String name = FileNameUtils.genFileName();
		// 保存为临时文件
		File tempFile = new File(root, name);
		try {
			file.transferTo(tempFile);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		try {
			// 保存详细图
			String detailName = name + "_m" + POINT + ext;
			File detailFile = new File(root, detailName);
			imageScale.resizeFix(tempFile, detailFile,
					86, 100);
			member.setAvatar(relPath + detailName);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		// 删除临时文件
		tempFile.delete();
		return true;
	}
	
	public void deleteImage(ShopMember entity, String uploadPath) {
		String detail = entity.getAvatar();
		if (!StringUtils.isBlank(detail)) {
			new File(uploadPath + detail).delete();
		}
		
	}
	
	public ShopMember save(ShopMember bean) {
		bean.init();
		if (bean.getGroup() == null) {
			bean.setGroup(shopMemberGroupMng.findGroupByScore(bean.getWebsite()
					.getId(), bean.getScore()));
		}
		dao.save(bean);
		return bean;
	}

	
	
	public ShopMember update(ShopMember bean,  Long groupId,
			String password, String email, Boolean disabled) {
		ShopMember entity = findById(bean.getId());
		// 修改密码，User
		userMng.updateUser(entity.getMember().getUser().getId(), password,
				email);
		// 是否禁用，Member，级联更新。
		if (disabled != null) {
			entity.getMember().setDisabled(disabled);
		}
		if (groupId != null) {
			entity.setGroup(shopMemberGroupMng.findById(groupId));
		}
		Updater<ShopMember> updater = new Updater<ShopMember>(bean);
		dao.updateByUpdater(updater);
		return entity;
	}
	
	public ShopMember update(ShopMember bean){
		Updater<ShopMember> updater = new Updater<ShopMember>(bean);
		dao.updateByUpdater(updater);
		return bean;
	}
	
	public ShopMember updateScore(ShopMember bean,Integer score){
		Integer scoreDb=dao.findById(bean.getId()).getScore();
		Integer scoreTotal=scoreDb+score;
		bean.setScore(scoreTotal);
		bean.setGroup(shopMemberGroupMng.findGroupByScore(bean.getWebsite()
				.getId(), scoreTotal));
		Updater<ShopMember> updater = new Updater<ShopMember>(bean);
		dao.updateByUpdater(updater);
		return bean;
	}

	public ShopMember update(ShopMember bean, Long groupId){
		Updater<ShopMember> updater = new Updater<ShopMember>(bean);
		updater.exclude(ShopMember.PROP_SCORE);
		bean=dao.updateByUpdater(updater);
		
		return bean;
	}

	public ShopMember deleteById(Long id) {
		ShopMember bean=dao.findById(id);
		Long userId=bean.getMember().getUser().getId();
		bean = dao.deleteById(id);
		userMng.deleteById(userId);
		return bean;
	}

	public ShopMember[] deleteByIds(Long[] ids) {
		ShopMember[] beans = new ShopMember[ids.length];
		for (int i = 0, len = ids.length; i < len; i++) {
			List<ShopMemberAddress> list=shopMemberAddressMng.findByMemberId(ids[i]);
			for(ShopMemberAddress address :list){
				shopMemberAddressMng.deleteById(address.getId(),ids[i]);
			}
			cartMng.deleteById(ids[i]);
			//还要删除订单哦 收藏夹 积分明细
			beans[i] = deleteById(ids[i]);
		}
		return beans;
	}
	
	public boolean usernameNotExist(String username) {
		return dao.countByUsername(username) <= 0;
	}
	
	@Transactional(readOnly=true)
	public ShopMember findByUsername(String username){
		ShopMember entity=dao.findByUsername(username);
		return entity;
	}
	
	@Transactional(readOnly=true)
	public List<ShopMember> getList(String username, Long groupId) {
		List<ShopMember> list=dao.getList(username, groupId);
		return list;
	}
	
	public ShopMember findUsername(String username) {
		return dao.findUsername(username);
	}
	
	@Autowired
	private CartMng cartMng;
	@Autowired
	private UserMng userMng;
	@Autowired
	private RoleMng roleMng;
	@Autowired
	private ShopMemberDao dao;
	@Autowired
	private MemberMng memberMng;
	@Autowired
	private WebsiteMng websiteMng;
	@Autowired
	private ImageScale imageScale;
	@Autowired
	private RealPathResolver realPathResolver;
	@Autowired
	private ShopMemberGroupMng shopMemberGroupMng; 
	@Autowired
	private ShopMemberAddressMng shopMemberAddressMng;
	

}